package mse.eai.jbpm.lotteryResultsProcess;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.jboss.logging.Logger;
import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class ParseWinnersList implements ActionHandler {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8082313114736763310L;
	private static final Logger log = Logger
			.getLogger(ParseWinnersList.class);

	public void execute(ExecutionContext context) throws Exception {

		log.info("Executing ---------->");
		
		try {
			log.info("Got from context: " + "fromESB  = " + context.getVariable("fromESB"));
			
			String xml = (String) context.getVariable("fromESB");

			// InputSource inputSource = new
			// InputSource("/_LIXO/GetWinnerListSOAPREsponse.xml");
			InputSource inputSource = new InputSource(new StringReader(xml));

			XPath xPath = XPathFactory.newInstance().newXPath();

			// XPathExpression
			// xPathExpression=xPath.compile("/catalog/journal/article[@date='January-2004']/title");
			// String title = xPathExpression.evaluate(inputSource);

			String expression = "//return";
			NodeList nodes = (NodeList) xPath.evaluate(expression, inputSource,
					XPathConstants.NODESET);

			int count = nodes.getLength();

			HashMap<Integer, Integer> prizes = new HashMap<Integer, Integer>();
			
			for (int i = 0; i < count; i++) {
				Node winnerNode = nodes.item(i);

				Node amountNode = (Node) xPath.evaluate("lindenEuros",
						winnerNode, XPathConstants.NODE);
				Node userIdNode = (Node) xPath.evaluate("userId", winnerNode,
						XPathConstants.NODE);

				int amount = Integer.parseInt(amountNode.getTextContent());
				int userId = Integer.parseInt(userIdNode.getTextContent());

				log.info ("User " + userId + " has won " + amount);
				prizes.put(userId, amount);
			}

			WinnersList lista = new WinnersList();
			lista.lista = new ArrayList<Winner>();
			for (Entry<Integer, Integer> entry : prizes.entrySet()) {
				Winner winner = new Winner();
				winner.amount = entry.getValue();
				winner.uid = entry.getKey();
				
				lista.lista.add(winner);
			}
			
			context.setVariable("winnersList", lista);
			
			log.info("Set in context: " + "winnersList  = " + lista);
			
			context.leaveNode(); 
			
		} catch (Exception ex) {
			log.error("Exception: ", ex);
			log.error("ProcessInstance will be suspended");
			context.getProcessInstance().suspend();
		}
		
		log.info("<--------------- Done");

	}

}